import axios from "axios";
import { getCookie } from "./cookie";

const service = axios.create({
  baseURL: "https://api-hmzs.itheima.net/v1",
  timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 1.获取token
    const token = getCookie();
    // 2.判断是否有token，如果有就添加到请求头中
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
